package dao

import (
	"fmt"
	"github.com/gogap/logs"
	"strconv"
	"strings"
	"sync"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/agentincome"
	"yundian/internel/app/models/dividendslog"
	"yundian/internel/app/models/ordersstatistics"
	"yundian/internel/app/models/placeincome"
	"yundian/internel/app/models/regions"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

type StatisticalDao struct {
}

func NewStatisticalDao() *StatisticalDao {
	return &StatisticalDao{}
}

type AgentStatisticalListRes struct {
	CreateAt                int64   `json:"create_at"`               //时间
	UserName                string  `json:"user_name"`               //代理商
	OrderTotal              int64   `json:"order_total"`             //订单数
	OrderMoney              float64 `json:"order_money"`             //完成订单的金额
	CompleteOrderEarnings   float64 `json:"complete_order_earnings"` //完成订单的收益
	RevocationTotal         int64   `json:"revocation_total"`        //撤销订单数量
	RevocationFee           float64 `json:"revocation_fee"`          //撤销订单的总金额
	RevocationOrderEarnings float64 `json:"revocation_total_money"`  //撤销订单的收益
}

type ManageSummaryStatist struct {
	Money  int64  `gorm:"column:money" json:"money"`
	SMoney int64  `gorm:"column:smoney" json:"sMoney"`
	Date   string `gorm:"column:date" json:"date"`
}

// 经营概况统计查询(其它类型)
func (d *StatisticalDao) ManageSummaryStatisticalTypeDao(isAdmin, paramIsAdmin uint8) *dingo.ErrorWrap {
	var SMoneysList []*ManageSummaryStatist
	var MoneysList []*ManageSummaryStatist
	var w sync.WaitGroup

	if isAdmin != helper.TypeNumIsAdminOperator && isAdmin != helper.TypeNumIsAdminAdministrator {
		return dingo.ErrorIf(nil, SMoneysList)
	}

	w.Add(2)
	go func() {
		SMoneysSql := `SELECT SUM(settlement_money)smoney,DATE_FORMAT(end_date, '%Y-%m-%d')date FROM (SELECT 
		o.settlement_money,our.end_date FROM orders_user_relevancy our LEFT JOIN users u ON our.user_id=u.id
		LEFT JOIN orders o ON o.trade_no=our.trade_no WHERE u.is_admin=? AND our.end_date>'1970-01-01' AND 
		o.state=5 GROUP BY our.trade_no,our.end_date) o GROUP BY end_date`
		if db := global.Orm.Raw(SMoneysSql, paramIsAdmin).Find(&SMoneysList); db.Error != nil {
			logs.Error(db.Error)
		}
		w.Done()
	}()
	go func() {
		moneySql := `SELECT SUM(dl.money)money,DATE_FORMAT(dl.end_date, '%Y-%m-%d')date FROM dividends_log dl LEFT JOIN 
		users u ON dl.user_id=u.id WHERE u.is_admin=? AND dl.end_date>'1970-01-01' GROUP BY dl.end_date`
		if db := global.Orm.Raw(moneySql, paramIsAdmin).Find(&MoneysList); db.Error != nil {
			logs.Error(db.Error)
		}
		w.Done()
	}()
	w.Wait()

	for _, item := range SMoneysList {
		for _, item1 := range MoneysList {
			if item.Date == item1.Date {
				item.Money = item1.Money
				break
			}
		}
	}

	return dingo.ErrorIf(nil, SMoneysList)
}

// 经营概况统计查询(运营商)
func (d *StatisticalDao) ManageSummaryStatisticalDao(isAdmin uint8) *dingo.ErrorWrap {
	var SMoneysList []*ManageSummaryStatist
	var MoneysList []*ManageSummaryStatist
	var w sync.WaitGroup

	if isAdmin != helper.TypeNumIsAdminOperator && isAdmin != helper.TypeNumIsAdminAdministrator {
		return dingo.ErrorIf(nil, SMoneysList)
	}

	w.Add(2)
	go func() {
		SMoneysSql := `SELECT SUM(settlement_money)smoney,DATE_FORMAT(our.end_date, '%Y-%m-%d')date FROM orders o LEFT JOIN orders_user_relevancy 
		our on o.trade_no = our.trade_no WHERE our.user_id=2 AND o.state=5 AND our.end_date>'1970-01-01' GROUP BY our.end_date`
		if db := global.Orm.Raw(SMoneysSql).Find(&SMoneysList); db.Error != nil {
			logs.Error(db.Error)
		}
		w.Done()
	}()
	go func() {
		moneySql := `SELECT SUM(money)money,DATE_FORMAT(dl.end_date, '%Y-%m-%d')date 
		FROM dividends_log dl WHERE dl.end_date>'1970-01-01' AND dl.user_id=2 GROUP BY dl.end_date`
		if db := global.Orm.Raw(moneySql).Find(&MoneysList); db.Error != nil {
			logs.Error(db.Error)
		}
		w.Done()
	}()
	w.Wait()

	for _, item := range SMoneysList {
		for _, item1 := range MoneysList {
			if item.Date == item1.Date {
				item.Money = item1.Money
				break
			}
		}
	}

	return dingo.ErrorIf(nil, SMoneysList)
}

//代理统计报表
func (d *StatisticalDao) AgentStatisticalListDao(userName string, selectTime string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	db := global.Orm

	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	var queryUser, queryTime string
	if userName != "" {
		queryUser = " AND o.user_name = " + "'" + userName + "'"
	}

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")

		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]

		queryTime = " AND date_format(FROM_UNIXTIME(o.create_at), '%Y-%m-%d ') >= DATE_FORMAT(FROM_UNIXTIME(" + startTime + "),'%Y-%m-%d') " +
			" AND date_format(FROM_UNIXTIME(o.create_at), '%Y-%m-%d ') <= DATE_FORMAT(FROM_UNIXTIME(" + endTime + "),'%Y-%m-%d') "
	}

	var agentStatisticalModel []AgentStatisticalListRes
	sqlStr := "SELECT " +
		"o.create_at AS create_at," +
		"o.user_name AS user_name," +
		"sum( o.money ) AS order_money," +
		"count( o.id ) AS order_total," +
		"count( o.id ) - sum( if( o.settlement_money = o.money,0,1 )) AS  revocation_total," +
		"sum( o.money - o.settlement_money ) AS revocation_fee," +
		"(sum( o.money ) * (u.profit_proportion/100)) complete_order_earnings," +
		"( sum( o.money - o.settlement_money ) / (u.profit_proportion/100) ) revocation_total_money  " +
		" FROM" +
		" orders o" +
		" LEFT JOIN users AS u ON o.user_id = u.id" +
		" WHERE 1 = 1 " + queryUser + queryTime +
		" GROUP BY DATE_FORMAT( FROM_UNIXTIME( o.create_at ), '%Y-%m-%d' ) ,o.user_name" +
		" ORDER BY  DATE_FORMAT( FROM_UNIXTIME( o.create_at ), '%Y-%m-%d' ) DESC" +
		" limit ?" +
		" offset ?"

	//var data []AgentStatisticalListRes
	//dbTestErr := db.Raw("SELECT create_at AS start_time  from orders where 1 = 1 GROUP BY user_name").Find(&data)
	//logs.Error(dbTestErr.Error)

	db.Raw(sqlStr, limit, offset).Find(&agentStatisticalModel)

	countSql := "select o.id from orders o WHERE 1 = 1 " + queryUser + queryTime + "  group by DATE_FORMAT( FROM_UNIXTIME( o.create_at ), '%Y-%m-%d' )"

	db.Raw(countSql).Count(&count)

	return dingo.ErrorIf(db.Error, agentStatisticalModel, count)
}

type PlaceStatisticalListRes struct {
	CreateAt        int64   `json:"create_at"`        //时间
	PlaceName       string  `json:"place_name"`       //网点名称
	OrderTotal      int64   `json:"order_total"`      //订单数
	OrderMoney      float64 `json:"complete_total"`   //完成订单数
	CompleteOrder   float64 `json:"complete_money"`   //完成订单的金额
	RevocationTotal int64   `json:"revocation_total"` //撤销订单数
	RevocationMoney float64 `json:"revocation_money"` //撤销订单的总金额
	NotPayTotal     int     `json:"not_pay_total"`    //未支付订单
}

//网点统计报表
func (d *StatisticalDao) PlaceStatisticalListDao(placeName string, selectTime string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	db := global.Orm
	var queryPlace, queryTime string

	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	if placeName != "" {
		queryPlace = " AND o.place_name = " + "'" + placeName + "'"
	}

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")

		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]

		queryTime = " AND date_format(FROM_UNIXTIME(o.create_at), '%Y-%m-%d ') >= DATE_FORMAT(FROM_UNIXTIME(" + startTime + "),'%Y-%m-%d') " +
			" AND date_format(FROM_UNIXTIME(o.create_at), '%Y-%m-%d ') <= DATE_FORMAT(FROM_UNIXTIME(" + endTime + "),'%Y-%m-%d') "
	}

	var placeStatisticalModel []PlaceStatisticalListRes
	sqlStr := " SELECT " +
		"o.create_at AS create_at," +
		"o.place_name AS place_name," +
		"count( o.id ) AS order_total," +
		"count( o.id ) - sum( IF ( o.state = 5, 0, 1 ) ) AS complete_total," +
		"sum(IF( o.state = 5,o.money,0)) AS complete_money," +
		"count( o.id ) - sum( IF ( o.state = 3, 0, 1 ) ) AS revocation_total," +
		"sum(IF( o.state = 3,o.money,0)) AS revocation_money, " +
		"count( o.id ) - sum( IF ( o.settlement_state = 1, 0, 1 ) ) AS not_pay_total" +
		" FROM" +
		" orders o" +
		" WHERE 1 = 1 " + queryPlace + queryTime +
		" GROUP BY DATE_FORMAT( FROM_UNIXTIME( o.create_at ), '%Y-%m-%d' ),o.user_name" +
		" ORDER BY  DATE_FORMAT( FROM_UNIXTIME( o.create_at ), '%Y-%m-%d' ) DESC" +
		" limit ?" +
		" offset ?"

	db.Raw(sqlStr, limit, offset).Scan(&placeStatisticalModel)

	countSql := "select o.id from orders o  WHERE 1 = 1 " + queryPlace + queryTime + "  group by DATE_FORMAT( FROM_UNIXTIME( o.create_at ), '%Y-%m-%d' )"

	db.Raw(countSql).Count(&count)

	return dingo.ErrorIf(db.Error, placeStatisticalModel, count)
}

type DeviceStatisticalListRes struct {
	CreateAt        int64   `json:"create_at"`        //时间
	DeviceName      string  `json:"device_name"`      //设备类型名称
	OrderTotal      int64   `json:"order_total"`      //订单数
	OrderMoney      float64 `json:"complete_total"`   //完成订单数
	CompleteOrder   float64 `json:"complete_money"`   //完成订单的金额
	RevocationTotal int64   `json:"revocation_total"` //撤销订单数
	RevocationMoney float64 `json:"revocation_money"` //撤销订单的总金额
}

//设备统计报表
func (d *StatisticalDao) DeviceStatisticalListDao(deviceTypeName string, selectTime string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	db := global.Orm
	var queryDevice, queryTime string
	if deviceTypeName != "" {
		queryDevice = " AND d.device_type_name = " + "'" + deviceTypeName + "'"
	}

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")

		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]

		queryTime = " AND date_format(FROM_UNIXTIME(o.create_at), '%Y-%m-%d ') >= DATE_FORMAT(FROM_UNIXTIME(" + startTime + "),'%Y-%m-%d') " +
			" AND date_format(FROM_UNIXTIME(o.create_at), '%Y-%m-%d ') <= DATE_FORMAT(FROM_UNIXTIME(" + endTime + "),'%Y-%m-%d') "
	}

	var deviceStatisticalModel []DeviceStatisticalListRes
	sqlStr := " SELECT " +
		"o.create_at AS create_at," +
		"d.device_type_name AS device_name," +
		"count( o.id ) AS order_total," +
		"count( o.id ) - sum( IF ( o.state = 5, 0, 1 ) ) AS complete_total," +
		"sum(IF( o.state = 5,o.money,0)) AS complete_money," +
		"count( o.id ) - sum( IF ( o.state = 3, 0, 1 ) ) AS revocation_total," +
		"sum(IF( o.state = 3,o.money,0)) AS revocation_money " +
		" FROM" +
		" orders o" +
		" LEFT JOIN devices AS d ON o.device_sn = d.device_sn " +
		" WHERE 1 = 1 " + queryDevice + queryTime +
		" GROUP BY DATE_FORMAT( FROM_UNIXTIME( o.create_at ), '%Y-%m-%d' ),o.device_sn" +
		" ORDER BY  DATE_FORMAT( FROM_UNIXTIME( o.create_at ), '%Y-%m-%d' ) DESC" +
		" limit ?" +
		" offset ?"

	db.Raw(sqlStr, limit, offset).Scan(&deviceStatisticalModel)

	countSql := "select count(1)  count from (select o.device_sn from orders o LEFT JOIN devices AS d ON o.device_sn = d.device_sn   WHERE 1 = 1 " + queryDevice + queryTime + "  group by o.device_sn  ) count"

	db.Raw(countSql).Count(&count)

	return dingo.ErrorIf(db.Error, deviceStatisticalModel, count)
}

type PlaceAccountCheckingListReq struct {
	Id         int    `json:"id"`          //网点ID
	PlaceName  string `json:"place_name"`  //网点名称
	Address    string `json:"address"`     //地址
	UserName   string `json:"user_name"`   //所属人
	ClassName  string `json:"class_name"`  //类型
	ProfitType int    `json:"profit_type"` //分成模式
	Status     int    `json:"status"`      //状态
	CreateAt   int    `json:"create_at"`   //加入时间
}

//网点对账单
func (d *StatisticalDao) PlaceAccountCheckingListDao(param *request.PlaceListReq) *dingo.ErrorWrap {

	var (
		count  int64
		limit  = param.PageSize
		offset = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().Table("places p")
	db.Select("p.id id,p.place_name place_name,p.address address,p.user_name user_name,p.class_name class_name,p.status status,p.create_at create_at,u.profit_type profit_type")
	db.Joins("left join users u on p.user_id = u.id")
	//网点查询
	if param.PlaceName != "" {

		db.Where(" p.place_name like ? ", fmt.Sprint("%", param.PlaceName, "%"))
	}

	//状态查询
	if param.Status != 0 {
		db.Where(" p.status = ?", param.Status)
	}

	//查询网点所属人
	if param.UserName != "" {
		db.Where(" p.user_name = ? ", param.UserName)
	}

	//是否查询上下级   --字段待实现

	//查询省份
	if param.RegionIds != "" {
		db.Where(" p.region_ids = ? ", param.RegionIds)
	}

	var placeAccountCheckingModel []PlaceAccountCheckingListReq

	db.Order(" p.create_at desc")
	db.Limit(limit).Offset(offset).Find(&placeAccountCheckingModel).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, placeAccountCheckingModel, count)
}

type ProjectStatisticalListRes struct {
	UserId        int     `json:"user_id"`        //用户编号
	UserName      string  `json:"user_name"`      //项目名称
	UserType      string  `json:"user_type"`      //角色
	OrderTotal    int     `json:"order_total"`    //订单数量
	CompleteMoney float64 `json:"complete_money"` //总营业额
	TransferMoney float64 `json:"transfer_money"` //总提现
	UserParent    int     `json:"user_parent"`    //代理数
	PlaceTotal    int     `json:"place_total"`    //网点数
}

//项目营业统计
func (d *StatisticalDao) ProjectStatisticalListDao(userName string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	db := global.Orm
	var queryUserName string
	if userName != "" {
		queryUserName = " AND u.user_name = " + "'" + userName + "'"
	}

	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	var projectStatisticalList []ProjectStatisticalListRes
	sqlStr := " SELECT " +
		"u.id AS user_id," +
		"u.name AS user_name," +
		"u.is_admin AS user_type," +
		"(select count(parent_id) from users where parent_id=u.id) AS user_parent," +
		"order_total," +
		"complete_money," +
		"transfer_money," +
		"place_total" +
		" FROM" +
		" users u" +
		" LEFT JOIN (SELECT user_id,count(o.id) AS order_total, sum(IF( o.state = 5,o.money,0)) AS complete_money FROM orders o GROUP BY user_id)  AS o ON u.id = o.user_id" +
		" LEFT JOIN (SELECT user_id,sum(c.transfer_money) AS transfer_money FROM cash_log c GROUP BY user_id )  AS c ON u.id = c.user_id" +
		" LEFT JOIN (SELECT user_id,count(p.id) AS place_total FROM places p GROUP BY user_id)  AS p ON u.id = p.user_id" +
		" WHERE 1 = 1 " + queryUserName +
		" GROUP BY u.id" +
		" limit ?" +
		" offset ?"

	db.Raw(sqlStr, limit, offset).Find(&projectStatisticalList)

	countSql := "select u.id from users u WHERE 1=1 " + queryUserName + " group by u.id"

	db.Raw(countSql).Count(&count)

	return dingo.ErrorIf(db.Error, projectStatisticalList, count)
}

type MonthStatisticalListReq struct {
	CreateAt        int     `json:"create_at"`        //统计日
	OrderTotal      int     `json:"order_total"`      //订单数
	CompleteTotal   int     `json:"complete_total"`   //完成订单数
	CompleteMoney   float64 `json:"complete_money"`   //完成营业额
	RevocationTotal int     `json:"revocation_total"` //撤销订单数
	RevocationMoney float64 `json:"revocation_money"` //撤销营业额
	FailureOrder    int     `json:"failure_order"`    //未支付订单
	TransferMoney   float64 `json:"transfer_money"`   //提现金额
	PlaceTotal      int     `json:"place_total"`      //新增网点数
	UserCount       int     `json:"user_count"`       //新增代理数
}

//月运营统计
func (d *StatisticalDao) MonthStatisticalListDao(userName string, selectMonth string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	db := global.Orm
	var queryUserName, queryTime string
	if userName != "" {
		queryUserName = " AND o.user_name = " + "'" + userName + "'"
	}

	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	if selectMonth != "" {
		queryTime = " AND date_format(FROM_UNIXTIME(o.create_at), '%Y-%m ') = " + "'" + selectMonth + " ' "
	}

	var monthStatisticalList []MonthStatisticalListReq

	sqlStr := " SELECT " +
		"o.create_at AS create_at," +
		"count( o.id ) AS order_total," +
		"count( o.id ) - sum( IF ( o.state = 5, 0, 1 ) ) AS complete_total," +
		"sum(IF( o.state = 5,o.money,0)) AS complete_money," +
		"count( o.id ) - sum( IF ( o.state = 3, 0, 1 ) ) AS revocation_total," +
		"sum(IF( o.state = 3,o.money,0)) AS revocation_money," +
		"count( o.id ) - sum( IF ( o.settlement_state = 1, 0, 1 ) ) AS failure_order," +
		"transfer_money," +
		"place_total," +
		"u.user_total AS user_count" +
		" FROM" +
		" orders o" +
		" LEFT JOIN (SELECT user_id,sum(c.transfer_money) AS transfer_money FROM cash_log c GROUP BY user_id )  AS c ON o.user_id = c.user_id" +
		" LEFT JOIN (SELECT user_id,COUNT(id) AS place_total FROM places WHERE TO_DAYS( NOW( ) ) - TO_DAYS( from_unixtime(create_at)) = 1  GROUP BY user_id) AS p ON o.user_id = c.user_id" +
		" LEFT JOIN (SELECT id,COUNT(id) AS user_total FROM users WHERE TO_DAYS( NOW( ) ) - TO_DAYS( from_unixtime(create_at)) = 1 GROUP BY id) AS u ON o.user_id = u.id" +
		" WHERE 1 = 1 " + queryUserName + queryTime +
		" GROUP BY  DATE_FORMAT(FROM_UNIXTIME( o.create_at), '%Y-%m-%d')" +
		" ORDER BY  DATE_FORMAT( FROM_UNIXTIME( o.create_at ), '%Y-%m-%d' ) DESC" +
		" limit ?" +
		" offset ?"

	db.Raw(sqlStr, limit, offset).Find(&monthStatisticalList)

	countSql := "select o.create_at from orders o WHERE 1=1 " + queryUserName + queryTime + " group by DATE_FORMAT( FROM_UNIXTIME( o.create_at ), '%Y-%m-%d' )"

	db.Raw(countSql).Count(&count)

	return dingo.ErrorIf(db.Error, monthStatisticalList, count)
}

type ProjectUserManagementListReq struct {
	Id            int     `json:"id"`             //用户编号
	UserName      string  `json:"user_name"`      //代理姓名
	Phone         string  `json:"phone"`          //代理手机号
	IsAdmin       int64   `json:"is_admin"`       //代理级别
	OrderTotal    int     `json:"order_total"`    //总订单数
	MoneyTotal    float64 `json:"money_total"`    //总营业额
	CompleteMoney float64 `json:"complete_money"` //总收益
	UserParent    int     `json:"user_parent"`    //代理数
	PlaceTotal    int     `json:"place_total"`    //网点数
	DeviceTotal   int     `json:"device_total"`   //设备数
}

//项目代理管理
func (d *StatisticalDao) ProjectUserManagementListDao(userName string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	db := global.Orm
	var queryUserName string
	if userName != "" {
		queryUserName = " AND u.name LIKE  " + "'%" + userName + "%'"

	}
	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	var projectUserManagementList []ProjectUserManagementListReq

	sqlStr := " SELECT " +
		"u.id ," +
		"u.name AS user_name," +
		"u.phone AS phone," +
		"u.is_admin AS is_admin," +
		"order_total," +
		"money_total," +
		"complete_money," +
		"(select count(parent_id) from users where parent_id=u.id) AS user_parent," +
		"place_total," +
		"device_total" +
		" FROM" +
		" users u" +
		" LEFT JOIN (SELECT user_id,count(o.id) AS order_total, sum(o.money) AS money_total, sum(IF( o.state = 5,o.money,0)) AS complete_money FROM orders o GROUP BY user_id)  AS o ON u.id = o.user_id" +
		" LEFT JOIN (SELECT user_id,COUNT(id) AS place_total FROM places  GROUP BY user_id) AS p ON u.id = p.user_id" +
		" LEFT JOIN (SELECT agent_user_id,COUNT(id) AS device_total FROM devices  GROUP BY agent_user_id) AS d ON u.id = d.agent_user_id" +
		" WHERE 1 = 1 " + queryUserName +
		" GROUP BY u.id" +
		" limit ?" +
		" offset ?"

	db.Raw(sqlStr, limit, offset).Find(&projectUserManagementList)

	countSql := "select u.id from users u WHERE 1=1 " + queryUserName + " group by u.id"

	db.Raw(countSql).Count(&count)

	return dingo.ErrorIf(db.Error, projectUserManagementList, count)

}

type ProjectPlaceManagementListReq struct {
	Id         int    `json:"id"`          //网点编号
	PlaceName  string `json:"place_name"`  //网点名称
	ClassName  string `json:"class_name"`  //网点类型
	UserName   string `json:"user_name"`   //商户
	ProfitType int    `json:"profit_type"` //分成方式
	Address    string `json:"address"`     //所属位置
	Status     int    `json:"status"`      //状态
	CreateAt   int    `json:"create_at"`   //创建时间
}

//项目网点管理
func (d *StatisticalDao) ProjectPlaceManagementListDao(placeName string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {

	db := global.Orm
	var queryPlaceName string
	if placeName != "" {
		queryPlaceName = " AND p.place_name LIKE " + "'%" + placeName + "%'"
	}
	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	var projectPlaceManagementList []ProjectPlaceManagementListReq

	sqlStr := " SELECT " +
		"p.id," +
		"p.place_name," +
		"p.class_name," +
		"p.user_name," +
		"profit_type," +
		"p.address," +
		"p.status," +
		"p.create_at" +
		" FROM" +
		" places p" +
		" LEFT JOIN (SELECT user_id, profit_type  FROM profits  GROUP BY user_id) AS pr ON p.user_id = pr.user_id" +
		" WHERE 1 = 1 " + queryPlaceName +
		" GROUP BY p.id" +
		" limit ?" +
		" offset ?"

	db.Raw(sqlStr, limit, offset).Find(&projectPlaceManagementList)

	countSql := "select p.id from places p WHERE 1=1 " + queryPlaceName + " group by p.id"

	db.Raw(countSql).Count(&count)

	return dingo.ErrorIf(db.Error, projectPlaceManagementList, count)
}

type ProjectOrderManagementListReq struct {
	TradeNo         string  `json:"trade_no"`         //订单号
	Title           string  `json:"title"`            //订单标题
	PlaceName       string  `json:"place_name"`       //网点名称
	DeviceSn        string  `json:"device_sn"`        //设备序列号
	SharedMode      string  `json:"shared_mode"`      //共享模式
	FeeMode         int     `json:"fee_mode"`         //收费模式
	UserName        string  `json:"user_name"`        //会员姓名
	Money           float64 `json:"money"`            //订单总金额
	PayMoney        float64 `json:"pay_money"`        //支付金额
	SettlementState int     `json:"settlement_state"` //结算状态
	State           int     `json:"state"`            //订单状态
	EndAt           int     `json:"end_at"`           //完结时间
	CreateAt        int     `json:"create_at"`        //创建时间
}

//项目订单管理
func (d *StatisticalDao) ProjectOrderManagementListDao(name string, endTime string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {

	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	db := global.Orm.Table("orders")
	db.Select("trade_no,title,place_name,device_sn,shared_mode,fee_mode,user_name,money,pay_money,settlement_state,state,end_at,create_at")
	if name != "" {
		db.Where("place_name like ? or trade_no like ? ", fmt.Sprint("%", name, "%"), fmt.Sprint("%", name, "%"))
		//db.Where("trade_no like ?", fmt.Sprint("%", name, "%"))
	}

	if endTime != "" {
		selectTimeArr := strings.Split(endTime, ",")

		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]

		db.Where("date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", startTime)
		db.Where("date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime)
	}

	var projectOrderManagementList []ProjectOrderManagementListReq

	db.Order("trade_no desc")
	db.Limit(limit).Offset(offset).Find(&projectOrderManagementList).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, projectOrderManagementList, count)
}

type SearchUserTypeListRes struct {
	Id       int    `json:"id"`
	Name     string `json:"name"`
	Phone    string `json:"phone"`
	UserName string `gorm:"column:user_name" json:"userName"`
}

func (d *StatisticalDao) SearchUserTypeListDao(name string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {

	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	var resData []SearchUserTypeListRes
	db := global.Orm.Table("users")
	db.Select("id,user_name,name,phone")

	if name != "" {
		db.Where(" name like ?", fmt.Sprint("%", name, "%"))
	}

	db.Order("id desc")
	db.Limit(limit).Offset(offset).Find(&resData).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, resData, count)
}

type SearchPlaceTypeListRes struct {
	Id        int    `column:"id" json:"id"`
	PlaceName string `column:"place_name" json:"place_name"`
	UserName  string `column:"user_name" json:"user_name"`
}

func (d *StatisticalDao) SearchPlaceTypeListDao(placeName string, userName string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {

	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	var resData []SearchPlaceTypeListRes
	db := global.Orm.Debug().Table("places")
	db.Select("id,place_name,user_name")

	if placeName != "" {
		db.Where(" place_name like ?", fmt.Sprint("%", placeName, "%"))
	}

	if userName != "" {
		db.Where(" user_name like ?", fmt.Sprint("%", userName, "%"))
	}
	//db.Group("place_name")
	db.Order("id desc")
	db.Limit(limit).Offset(offset).Find(&resData).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, resData, count)
}

type SearchDeviceTypeListRes struct {
	DeviceTypeName string `json:"device_type_name"`
}

func (d *StatisticalDao) SearchDeviceTypeListDao(deviceType string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {

	var (
		count  int64
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	var resData []SearchDeviceTypeListRes
	db := global.Orm.Table("devices")
	db.Select("device_type_name")

	if deviceType != "" {
		db.Where(" device_type_name like ?", fmt.Sprint("%", deviceType, "%"))
	}
	db.Group("device_type_name")
	db.Order("id desc")
	db.Limit(limit).Offset(offset).Find(&resData).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, resData, count)
}

// 获取省、市、县
func (d *StatisticalDao) GetRegionsList(level int) *dingo.ErrorWrap {
	lst := make([]*regions.RegionModel, 0)
	db := global.Orm.Debug().Table("lc_tencent_regions")
	db.Where("level = ?", 1)

	db.Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

func (d *StatisticalDao) AgentIncomeListDao(userId int, selectTime string, monthType int, sharedMode string, baseListReq *request.BaseListReq, loginUserId int, isAdmin uint8) *dingo.ErrorWrap {
	var (
		count  int64
		list   []agentincome.AgentIncomeModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	db := global.Orm.Debug().Table("agent_income a").
		Select("a.*,u.name as name,u.user_name as agent_user_name,u.phone as phone").
		Joins("LEFT JOIN ( SELECT u.id, u.name,u.user_name,u.phone FROM users u) AS u ON a.agent_user_id = u.id")
	if userId > 0 {
		db.Where("a.agent_user_id = ? ", userId)
	}

	if sharedMode != "" {
		db.Where("a.shared_mode = ? ", sharedMode)
	}

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]

		//日统计
		if monthType == 1 {
			db.Where("a.income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", startTime)
			db.Where("a.income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime)
		} else {
			db.Where("a.income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", startTime)
			db.Where("a.income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", endTime)
		}

	}
	// 如果是运营商或代理商登录，只展示旗下所有商户
	if isAdmin > helper.TypeNumIsAdminStaff {
		// 获取该用户下的所有代理商的用户ID
		pidArr := []int{loginUserId}
		userIdArr := make([]int, 0)
		userIdArr = append(userIdArr, loginUserId)
		isRecursive := true
		// 递归 无限查询下级
		for isRecursive {
			tempUserIdArr := NewUserDao().GetUserIdByPid(pidArr).Unwrap().([]int)

			if len(tempUserIdArr) == 0 {
				isRecursive = false
			} else {
				userIdArr = append(userIdArr, tempUserIdArr...)
				pidArr = tempUserIdArr
				//log.Println("当前pid数组：",pidArr)
				//log.Println("当前userIdArr数组：",userIdArr)
			}
		}
		db.Where("a.agent_user_id in (?)", userIdArr)
		//db.Where("u.parent_id = ? ", loginUserId)
	}
	if monthType == 2 {
		db.Group("date_format( a.income_day, '%Y-%m' ),a.agent_user_id")
	}

	db.Order("a.income_day desc")
	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) AgentIncomeMonthListDao(userId int, selectTime string, monthType int, sharedMode string, baseListReq *request.BaseListReq, loginUserId int, isAdmin uint8) *dingo.ErrorWrap {
	var (
		count  int64
		list   []agentincome.AgentIncomeModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	db := global.Orm.Debug().Table("agent_income a").
		Select("a.places_total, date_format( a.income_day, '%Y-%m' ) income_day,SUM(a.complete_count) complete_count, " +
			"SUM(a.cancel_count) cancel_count, SUM(a.trade_total) trade_total, SUM(a.total_money) total_money, SUM(a.divinds_money) divinds_money ," +
			"u.name as name,u.user_name as agent_user_name,u.phone as phone").
		Joins("LEFT JOIN ( SELECT u.id, u.name,u.user_name,u.phone FROM users u) AS u ON a.agent_user_id = u.id")

	if userId > 0 {
		db.Where("a.agent_user_id = ? ", userId)
	}

	if sharedMode != "" {
		db.Where("a.shared_mode = ? ", sharedMode)
	}

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]

		//日统计
		if monthType == 2 {
			db.Where("date_format( a.income_day, '%Y-%m' ) >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", startTime)
			db.Where("date_format( a.income_day, '%Y-%m' ) <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", endTime)
		}

	}
	// 如果是运营商或代理商登录，只展示旗下所有商户
	if isAdmin > helper.TypeNumIsAdminStaff {
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)
		db.Where("a.agent_user_id in (?)", userIdArr)

	}

	db.Group("date_format( a.income_day, '%Y-%m' ),a.agent_user_id")

	db.Order("a.income_day desc")
	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) BranchIncomeListDao(userName string, selectTime string, monthType int, sharedMode string, baseListReq *request.BaseListReq, loginUserId int, isAdmin uint8, isPlace uint8) *dingo.ErrorWrap {
	var (
		count  int64
		list   []agentincome.BranchIncomeModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	db := global.Orm.Debug().Table("branch_income")

	if userName != "" {
		//db.Where("agent_user_name = ? ", userName)
		db.Where("agent_user_id = ? ", 221)
	}
	if sharedMode != "" {
		db.Where("shared_mode = ? ", userName)
	}

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]
		//日统计
		if monthType == 1 {
			db.Where("income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", startTime)
			db.Where("income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime)
		} else {
			db.Where("income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", startTime)
			db.Where("income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", endTime)
		}
	}

	// 如果是运营商或代理商登录，只展示旗下所有商户
	if isPlace == 3 {

		// 获取该用户下的所有代理商的用户ID
		pidArr := []int{loginUserId}
		userIdArr := make([]int, 0)
		userIdArr = append(userIdArr, loginUserId)
		isRecursive := true
		// 递归 无限查询下级
		for isRecursive {
			tempUserIdArr := NewUserDao().GetUserIdByPid(pidArr).Unwrap().([]int)

			if len(tempUserIdArr) == 0 {
				isRecursive = false
			} else {
				userIdArr = append(userIdArr, tempUserIdArr...)
				pidArr = tempUserIdArr
				//log.Println("当前pid数组：",pidArr)
				//log.Println("当前userIdArr数组：",userIdArr)
			}
		}
		db.Where("agent_user_id in (?)", userIdArr)
		//db.Where("u.parent_id = ? ", loginUserId)
	}

	if monthType == 2 {
		db.Group("date_format( income_day, '%Y-%m' ),agent_user_id")
	}
	db.Order("income_day desc")
	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) OrdersStatisticsListDao(userId int, isAdmin uint8, placeName string, selectTime string, monthType int, sharedMode string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	var (
		count  int64
		list   []ordersstatistics.OrdersstatisticsModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	db := global.Orm.Debug().
		Table("orders_statistics")

	if placeName != "" {
		db.Where("place_name =? ", placeName)
	}
	if sharedMode != "" {
		db.Where("shared_mode =? ", sharedMode)
	}
	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]
		//日统计
		if monthType == 1 {
			db.Where("date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", startTime)
			db.Where("date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime)
		} else {
			db.Where("date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", startTime)
			db.Where("date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", endTime)
		}
	}

	// 如果是运营商或代理商登录，只展示旗下所有商户
	if isAdmin > helper.TypeNumIsAdminStaff {

		// 获取该用户下的所有代理商的用户ID
		//pidArr := []int{userId}
		//userIdArr := make([]int, 0)
		////查询自己的本身的
		//
		//userIdArr = append(userIdArr, userId)
		//isRecursive := true
		//// 递归 无限查询下级
		//for isRecursive {
		//	tempUserIdArr := NewUserDao().GetUserIdByPid(pidArr).Unwrap().([]int)
		//
		//	if len(tempUserIdArr) == 0 {
		//		isRecursive = false
		//	} else {
		//
		//		userIdArr = append(userIdArr, tempUserIdArr...)
		//		pidArr = tempUserIdArr
		//		//log.Println("当前pid数组：",pidArr)
		//		//log.Println("当前userIdArr数组：",userIdArr)
		//	}
		//}
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		db.Where("agent_user_id in (?)", userIdArr)
		//db.Where("u.parent_id = ? ", loginUserId)
	}

	if monthType == 2 {
		db.Group("DATE_FORMAT(FROM_UNIXTIME(place_create_at), '%Y-%m'),place_id")

	}
	db.Order("create_at desc")
	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) PlaceStatisticsListDao(userId int, isAdmin uint8, placeName string, selectTime string, monthType int, sharedMode string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	var (
		count  int64
		list   []*placeincome.PlaceIncomeModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	db := global.Orm.Debug().
		Table("place_income s").
		Select("s.id", "s.place_id",
			"s.settlement_money", "s.device_total",
			"s.income_day", "s.shared_mode",
			"s.agent_user_id", "s.place_name",
			"s.income", "s.order_count", "s.complete_count",
			"p.create_at as place_create_at",
			"p.province", "p.city", "IF(p.hotel_id='',0, p.hotel_id) hotel_id").
		Joins("left join places p on p.id = s.place_id")

	if placeName != "" {
		db.Where("p.place_name =? ", placeName)
	}
	if sharedMode != "" {
		db.Where("s.shared_mode =? ", sharedMode)
	}
	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]
		//日统计
		if monthType == 1 {
			db.Where("s.income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", startTime)
			db.Where("s.income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime)
		} else {
			db.Where("s.income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", startTime)
			db.Where("s.income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", endTime)
		}
	}

	// 如果是运营商或代理商登录，只展示旗下所有商户
	if isAdmin > helper.TypeNumIsAdminStaff {

		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		db.Where("s.agent_user_id in (?)", userIdArr)
		//db.Where("u.parent_id = ? ", loginUserId)
	}

	if monthType == 2 {
		db.Group("DATE_FORMAT(FROM_UNIXTIME(s.place_create_at), '%Y-%m'),s.place_id")

	}
	db.Order("s.income_day desc")
	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) PlaceStatisticsAllListDao(userId int, isAdmin, isDraw uint8, placeName string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	var (
		count  int64
		list   []*placeincome.PlaceIncomeAllModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	fields := `p.id place_id,p.create_at place_create_at,p.create_at,p.province,p.city,p.place_name,p.hotel_id,COUNT(1)
	scan_count,SUM(IF(o.state=5, 1, 0))complete_count,SUM(IF(o.state=5, settlement_money, 0))settlement_money`
	db := global.Orm.Debug().Table("places p").Select(fields)
	db.Joins("LEFT JOIN (SELECT * FROM logistics GROUP BY place_id) l ON p.id = l.place_id")
	db.Joins("LEFT JOIN orders o on p.id = o.place_id")

	var placeIdArr []int
	if isAdmin != helper.TypeNumIsAdminOperator {
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placeIdArr = NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		//分公司
		if isAdmin == helper.TypeNumIsAdminBranch {
			placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)
			placeIdArr = append(placesBranchIds, placesBranchIds...)
			//去重网点
			placeIdArr = utils.RemoveRepByMap(placesBranchIds)
		}

		if len(placeIdArr) == 0 {
			return dingo.ErrorIf(db.Error, list, count)
		}
		count = int64(len(placeIdArr))
		db.Where("p.id in(?)", placeIdArr)

		//if isDraw != helper.TypeNumIsDrawOpen {
		//	db.Where("o.is_draw<>? and o.is_tianhai=0", helper.TypeNumIsDrawOpen)
		//} else {
		//	db.Where("(is_draw<>? or (is_draw=? and p.agent_user_id>2)) and o.is_tianhai=0", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen)
		//}
	} else {
		if placeName == `` {
			global.Orm.Raw(" select count(1)  FROM places ").Find(&count)
		}
	}

	db.Where("o.is_draw<>? and o.is_tianhai=0", helper.TypeNumIsDrawOpen)

	if placeName != `` {
		db.Where("p.place_name=?", placeName)
		global.Orm.Raw(" select count(1)  FROM places where place_name=?", placeName).Find(&count)
	}

	//db.Group("p.id").Order("p.id DESC").Limit(limit).Offset(offset).Find(&list).Count(&count)
	db.Group("p.id").Order("p.id DESC").Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)

	if len(list) == 0 || db.Error != nil {
		return dingo.ErrorIf(db.Error, list, count)
	}

	// 激活设备量/有产设备量/收益 分批查询
	type countList struct {
		Total   int
		PlaceId int `gorm:"column:place_id"`
	}
	var targetPleceIds []int
	var deviceCountList []countList
	var activeDeviceCountList []countList
	var incomeList []countList

	for _, item := range list {
		targetPleceIds = append(targetPleceIds, item.PlaceId)
	}

	deviceCountSql := `SELECT COUNT(1) total, place_id FROM devices WHERE place_id IN (?) GROUP BY place_id`
	activeDeviceCounCountSql := `SELECT COUNT(1) total, place_id FROM (SELECT device_sn, place_id FROM 
	orders WHERE place_id IN (?) GROUP BY place_id,device_sn)o GROUP BY place_id`
	incomeCountSql := `SELECT SUM(dl.money) total,p.id place_id FROM places p LEFT JOIN dividends_log dl ON 
	p.id=dl.place_id AND p.user_id=dl.user_id WHERE p.id IN (?) AND dl.money > 0 GROUP BY p.id,p.user_id`
	global.Orm.Debug().Raw(deviceCountSql, targetPleceIds).Find(&deviceCountList)
	global.Orm.Debug().Raw(activeDeviceCounCountSql, targetPleceIds).Find(&activeDeviceCountList)
	global.Orm.Debug().Raw(incomeCountSql, targetPleceIds).Find(&incomeList)

	for _, item := range list {
		for _, dev := range deviceCountList {
			if dev.PlaceId == item.PlaceId {
				item.DeviceCount = int64(dev.Total)
			}
		}
		for _, adev := range activeDeviceCountList {
			if adev.PlaceId == item.PlaceId {
				item.ActiveDevCount = int64(adev.Total)
			}
		}
		for _, income := range incomeList {
			if income.PlaceId == item.PlaceId {
				item.Income = int64(income.Total)
			}
		}
	}

	//	var isDrawAndIsTianHai, notAdmin, queryPlaceName string
	//
	//	if placeName != `` {
	//		queryPlaceName = ` and  p.place_name = ? `
	//	}
	//
	//	if isAdmin != 2 {
	//		isDrawAndIsTianHai = ` WHERE is_draw != 1 and is_tianhai =0 `
	//		notAdmin = ` p.id in(?) `
	//	} else {
	//		isDrawAndIsTianHai = ``
	//		notAdmin = ``
	//	}
	//
	//	sql := `SELECT
	//	p.id,
	//	IFNULL(settlementMoney,0) as settlement_money ,
	//	IFNULL(deviceTotal,0) as device_count ,
	//	p.user_id,
	//	p.place_name,
	//	IFNULL(incomeTotal,0) as income ,
	//	IFNULL(orderCount,0) as scan_count ,
	//	IFNULL(completeCount,0) as complete_count ,
	//	IFNULL(active_dev_count,0) as active_dev_count ,
	//
	//	p.create_at AS place_create_at,
	//	p.province,
	//	p.city,
	//IF
	//	( p.hotel_id = '', 0, p.hotel_id ) hotel_id
	//FROM
	//	places p
	//	LEFT JOIN ( SELECT SUM( settlement_money ) settlementMoney, sum( IF ( state = 5, 0, 1 ) )  completeCount,sum( IF ( state != 0, 0, 1 ) )  orderCount,place_id FROM orders ` + isDrawAndIsTianHai + ` GROUP BY place_id ) AS o ON o.place_id = p.id
	//	LEFT JOIN ( SELECT count(1) deviceTotal,place_id FROM devices GROUP BY place_id  ) AS d ON d.place_id = p.id
	//	LEFT JOIN ( SELECT sum(money) incomeTotal,place_id,user_id FROM dividends_log GROUP BY place_id,user_id ) AS dl ON dl.place_id = p.id and dl.user_id = p.user_id
	//	LEFT JOIN ( select count(1) as active_dev_count,place_id  from (SELECT device_sn as total,place_id FROM orders ` + isDrawAndIsTianHai + ` group by device_sn,place_id) orders GROUP BY place_id) AS od ON od.place_id = p.id
	//	WHERE 1 = 1
	//	` + notAdmin + queryPlaceName + `
	//	ORDER BY settlement_money desc
	//	limit ?
	//	offset ? `
	//
	//	db := global.Orm.Debug()
	//	if isAdmin != 2 {
	//		db.Raw(sql, placeIdArr, limit, offset).Find(&list)
	//		count = int64(len(placeIdArr))
	//	} else {
	//		db.Raw(sql, limit, offset).Find(&list)
	//		db.Raw(" select count(1)  FROM places ").Find(&count)
	//	}

	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) PlaceStatisticsDayListDao(userId int, isAdmin, isDraw uint8, placeName, selectTime string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	var (
		count  int64
		list   []*placeincome.PlaceIncomeAllModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	var isDrawAndIsTianHai, notAdmin, queryPlaceName, selectTimeSql string

	if placeName != "" {
		queryPlaceName = ` and  p.place_name = ? `
	}

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]
		//月统计
		selectTimeSql = " date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') >= DATE_FORMAT(FROM_UNIXTIME(" + startTime + "),'%Y-%m-%d' AND " +
			" date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') <= DATE_FORMAT(FROM_UNIXTIME(" + endTime + "),'%Y-%m-%d'"
	}

	if isDraw != 1 {
		isDrawAndIsTianHai = ` WHERE is_draw != 1 and is_tianhai =0 `
	}

	if isAdmin != 2 {
		notAdmin = ` p.id in(?) `
	} else {
		isDrawAndIsTianHai = ``
		notAdmin = ``
	}

	sql := `SELECT
	s.id,
	s.place_id,
	s.device_total,
	s.income_day,
	s.shared_mode,
	s.agent_user_id,
	s.place_name,
	IFNULL(settlementMoney,0) as settlement_money ,
	IFNULL(completeCount,0) as complete_count ,
  IFNULL(incomeTotal,0) as income ,
	IFNULL(activeDevCount,0) as active_dev_count ,
	IFNULL(orderCount,0) asorder_count,
	s.agent_user_id,
	p.create_at AS place_create_at,
	p.province,
	p.city,
IF
	( p.hotel_id = '', 0, p.hotel_id ) hotel_id 
FROM
	place_income s
	LEFT JOIN places p ON p.id = s.place_id 
	
	LEFT JOIN ( SELECT SUM( settlement_money ) settlementMoney,	sum( IF ( state = 5, 1, 0 ) ) completeCount, 	sum( IF ( state >0, 1, 0 ) ) AS orderCount,place_id, DATE_FORMAT( FROM_UNIXTIME(  end_at ), '%Y-%m-%d' ) as  date FROM orders  ` + isDrawAndIsTianHai + `   GROUP BY place_id,date ) AS o ON o.place_id = p.id and  o.date = s.income_day
	
	LEFT JOIN ( SELECT sum(money) incomeTotal,place_id,user_id,DATE_FORMAT( FROM_UNIXTIME(  create_at ), '%Y-%m-%d' ) date FROM dividends_log GROUP BY date, place_id,user_id ) AS dl ON dl.place_id = p.id and dl.user_id = p.user_id and dl.date = s.income_day
	

	LEFT JOIN ( select count(1) as activeDevCount,place_id,date  from (SELECT device_sn as total,place_id,DATE_FORMAT( FROM_UNIXTIME(  create_at ), '%Y-%m-%d' ) date FROM orders    ` + isDrawAndIsTianHai + `   group by device_sn,place_id,date) orders GROUP BY place_id,date) AS od ON od.place_id = p.id and od.date = s.income_day
	WHERE 1 = 1  
	` + notAdmin + queryPlaceName + selectTimeSql + `
ORDER BY
	s.income_day DESC  
	limit ? 
	offset ? `

	db := global.Orm.Debug()
	if isAdmin != 2 {
		db.Raw(sql, placeIdArr, limit, offset).Find(&list)
		count = int64(len(placeIdArr))
	} else {
		db.Raw(sql, limit, offset).Find(&list)
		db.Raw(" select count(1)  FROM places ").Find(&count)
	}

	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) PlaceStatisticsMonthListDao(userId int, isAdmin, isDraw uint8, placeName string, selectTime string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	var (
		count  int64
		list   []*placeincome.PlaceIncomeAllModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	var isDrawAndIsTianHai, notAdmin, queryPlaceName, selectTimeSql string

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]
		//月统计
		selectTimeSql = " AND DATE_FORMAT(s.income_day,'%Y-%m') >= DATE_FORMAT(FROM_UNIXTIME(" + startTime + "),'%Y-%m') AND" +
			"  DATE_FORMAT(s.income_day,'%Y-%m') <= DATE_FORMAT(FROM_UNIXTIME(" + endTime + "),'%Y-%m')"
	}

	if placeName != "" {
		queryPlaceName = ` and  p.place_name =  ` + "'" + placeName + "'"
	}

	if isDraw != 1 {
		isDrawAndIsTianHai = ` WHERE is_draw != 1 and is_tianhai =0 `
	}

	if isAdmin != 2 {
		notAdmin = ` and  p.id in(?) `
	} else {
		isDrawAndIsTianHai = ``
		notAdmin = ``
	}

	sql := `SELECT
	s.id,
	s.place_id,
	s.device_total as device_count,
	DATE_FORMAT(s.income_day,'%Y-%m') income_day,
	s.shared_mode,
	s.agent_user_id,
	p.place_name,
	IFNULL(settlementMoney,0) as settlement_money ,
	IFNULL(completeCount,0) as complete_count ,
  	IFNULL(incomeTotal,0) as income ,
	IFNULL(activeDevCount,0) as active_dev_count ,
	IFNULL(orderCount,0) as scan_count,
	s.agent_user_id,
	p.create_at AS place_create_at,
	p.province,
	p.city,
IF
	( p.hotel_id = '', 0, p.hotel_id ) hotel_id 
FROM
	place_income s
	LEFT JOIN places p ON p.id = s.place_id 
	
	LEFT JOIN ( SELECT SUM( settlement_money ) settlementMoney,	sum( IF ( state = 5, 1, 0 ) ) completeCount, 	sum( IF ( state >0, 1, 0 ) ) AS orderCount,place_id, DATE_FORMAT( FROM_UNIXTIME(  end_at ), '%Y-%m' ) as  date FROM orders   ` + isDrawAndIsTianHai + `   GROUP BY place_id,date ) AS o ON o.place_id = p.id and  o.date = DATE_FORMAT(s.income_day,'%Y-%m')
	
	LEFT JOIN ( SELECT sum(money) incomeTotal,place_id,user_id,DATE_FORMAT( FROM_UNIXTIME(  create_at ), '%Y-%m' ) date FROM dividends_log GROUP BY date, place_id,user_id ) AS dl ON dl.place_id = p.id and dl.user_id = p.user_id and dl.date = DATE_FORMAT(s.income_day,'%Y-%m')

	LEFT JOIN ( select count(1) as activeDevCount,place_id,date  from (SELECT device_sn as total,place_id,DATE_FORMAT( FROM_UNIXTIME(  create_at ), '%Y-%m' ) date FROM orders   ` + isDrawAndIsTianHai + `  group by device_sn,place_id,date) orders GROUP BY place_id,date) AS od ON od.place_id = p.id and od.date = DATE_FORMAT(s.income_day,'%Y-%m')
	WHERE 1=1   
	` + notAdmin + queryPlaceName + selectTimeSql + `
GROUP BY DATE_FORMAT(s.income_day,'%Y-%m'),s.place_id
ORDER BY
	DATE_FORMAT(s.income_day,'%Y-%m') DESC   
	limit ? 
	offset ? `

	db := global.Orm.Debug()
	if isAdmin != 2 {
		db.Raw(sql, placeIdArr, limit, offset).Find(&list)

		countSql := ` select count(1)  from(
 SELECT  s.place_id, s.income_day  FROM place_income s 
LEFT JOIN places p ON p.id = s.place_id WHERE  1= 1
 ` + notAdmin + queryPlaceName + selectTimeSql + `
 GROUP BY
 DATE_FORMAT( s.income_day, '%Y-%m' ),
 s.place_id) as a		 		
`

		db.Raw(countSql, placeIdArr).Find(&count)
	} else {
		db.Raw(sql, limit, offset).Find(&list)
		countSql := ` select count(1)  from(
 SELECT  s.place_id, s.income_day  FROM place_income s WHERE  1= 1
 ` + notAdmin + queryPlaceName + selectTimeSql + `
 GROUP BY
 DATE_FORMAT( s.income_day, '%Y-%m' ),
 s.place_id) as a		 		
`

		db.Raw(countSql).Find(&count)
	}

	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) DividendsListDao(placeId int, selectTime string, userId int, tradeNo string, sharedMode string, baseListReq *request.BaseListReq, loginUserId int, isAdmin uint8) *dingo.ErrorWrap {
	var (
		count  int64
		list   []dividendslog.DividendsLog
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	db := global.Orm.Table("dividends_log")
	db.Where("is_tianhai = ?", 0)

	if userId > 0 {
		db.Where("user_id = ? ", userId)
	}

	if sharedMode != "" {
		db.Where("shared_mode =? ", sharedMode)
	}

	if tradeNo != "" {
		db.Where(" trade_no like ? ", fmt.Sprint("%", tradeNo, "%"))

	}

	if placeId > 0 {
		db.Where("place_id =? ", placeId)
	}

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]
		db.Where("date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') ", startTime)
		db.Where("date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') ", endTime)
	}

	// 如果是运营商或代理商登录，只展示旗下所有商户
	//if isAdmin == 3 {
	//	userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)
	//	db.Where("user_id in (?)", userIdArr)
	//	//db.Where("u.parent_id = ? ", loginUserId)
	//}
	if isAdmin > 3 {
		userIdArr := NewUserDao().QueryChildUserIds(loginUserId).Unwrap().([]int)
		db.Where("user_id in (?)", userIdArr)
		//db.Where("u.parent_id = ? ", loginUserId)
	}

	//db.Group("place_name")
	db.Order("create_at desc")
	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) PlaceStatisticsExportListDao(userId int, isAdmin uint8, placeName string, selectTime string, monthType int, sharedMode string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	var (
		count  int64
		list   []*placeincome.PlaceIncomeExportModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	db := global.Orm.Debug().
		Table("place_income s").
		Select("s.place_id", "s.settlement_money",
			"s.device_total", "s.income_day", "s.agent_user_id",
			"s.place_name", "lo.receive_time", "lo.return_time",
			"s.income", "s.order_count", "s.complete_count",
			"firs_date as first_order_date", "s.scan_code_user",
			"p.create_at as place_create_at", "lo.logistics_order_no",
			"p.province", "p.city", "IF(p.hotel_id='',0, p.hotel_id) hotel_id",
			"lo.return_status", "IF(lo.status = 3,1,0) active_status").
		Joins("left join places p on p.id = s.place_id").
		Joins("left join logistics lo on lo.place_id =s.place_id").
		Joins("left join (SELECT DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) as firs_date,place_id FROM (SELECT create_at,place_id FROM orders GROUP BY create_at  ORDER BY create_at ASC) orders1  GROUP BY place_id ORDER BY firs_date asc) o on o.place_id =s.place_id")

	if placeName != "" {
		db.Where("p.place_name =? ", placeName)
	}

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]
		//日统计
		if monthType == 1 {
			db.Where("s.income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", startTime)
			db.Where("s.income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime)
		} else {

			db.Where("s.income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", startTime)
			db.Where("s.income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", endTime)
		}
	}

	// 如果是运营商或代理商登录，只展示旗下所有商户
	if isAdmin != helper.TypeNumIsAdminOperator {

		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		db.Where("s.agent_user_id in (?)", userIdArr)
		//db.Where("u.parent_id = ? ", loginUserId)
	}

	if monthType == 2 {
		db.Group("DATE_FORMAT(FROM_UNIXTIME(s.place_create_at), '%Y-%m'),s.place_id")

	}
	db.Order("s.income_day desc")
	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)

	//查询分红
	incomeMap := map[string]int64{}
	var incomeModel []*placeincome.PlaceIncomeModel
	incomeSql := "SELECT SUM(money) as income,DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) as income_day ,user_id as agent_user_id ,place_id FROM dividends_log Where 1= 1  GROUP BY income_day,agent_user_id,place_id"
	global.Orm.Debug().Raw(incomeSql).Find(&incomeModel)
	for _, v := range incomeModel {
		incomeMap[strconv.Itoa(v.PlaceId+v.AgentUserId)+v.IncomeDay] = v.Income
	}

	ordersMap := map[string]placeincome.StatisticsPlaceOrders{}
	var ordersModel []placeincome.StatisticsPlaceOrders
	//查询网点统计的订单
	ordersSql := "SELECT sum(IF ( state = 5, settlement_money, 0 )  ) AS settlement_money ,sum( IF ( state >0, 1, 0 ) ) AS order_count, SUM( IF ( state = 5, 1, 0 ) ) complete_count, SUM( IF ( state = 3, 1, 0 ) ) cancel_count,DATE_FORMAT( FROM_UNIXTIME( end_at ), '%Y-%m-%d' ) income_day,place_id,shared_mode FROM orders Where 1= 1 AND is_tianhai=0 AND is_draw<>1  GROUP BY income_day,place_id"
	global.Orm.Debug().Raw(ordersSql).Find(&ordersModel)
	for _, v := range ordersModel {
		ordersMap[strconv.Itoa(v.PlaceId)+v.IncomeDay] = v
	}

	//赋值
	for _, lst := range list {
		lst.DeviceCount = lst.DeviceTotal
		//分红收益
		if v, ok := incomeMap[strconv.Itoa(lst.PlaceId+lst.AgentUserId)+lst.IncomeDay]; ok {
			lst.Income = v
		} else {
			lst.ActiveDevCount = 0
		}

		//订单
		if v, ok := ordersMap[strconv.Itoa(lst.PlaceId)+lst.IncomeDay]; ok {
			lst.ScanCount = v.OrderCount
			lst.CompleteCount = v.CompleteCount
			lst.CompleteCount = v.CompleteCount
			lst.SettlementMoney = v.SettlementMoney
		} else {
			lst.ScanCount = 0
			lst.CompleteCount = 0
			lst.CompleteCount = 0
			lst.SettlementMoney = 0
		}

	}

	return dingo.ErrorIf(db.Error, list, count)
}
func (d *StatisticalDao) PlaceStatisticsExportMonthListDao(userId int, isAdmin, isDraw uint8, placeName string, selectTime string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {

	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	var (
		count  int64
		list   []*placeincome.PlaceIncomeExportModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	var isDrawAndIsTianHai string
	isDrawAndIsTianHai = ` WHERE is_draw != 1 and is_tianhai =0 `

	db := global.Orm.Debug().Table("place_income s").
		Select(
			"s.place_id",
			"IFNULL(settlementMoney,0) as settlement_money ",
			"activeDevCount AS device_total", "DATE_FORMAT(s.income_day,'%Y-%m') as income_day",
			"s.place_name", "lo.receive_time", "lo.return_time",
			"incomeTotal AS income", "orderCount AS order_count", "completeCount AS complete_count",
			"firs_date as first_order_date", "SUM(s.scan_code_user) scan_code_user",
			"p.create_at as place_create_at", "lo.logistics_order_no",
			"p.province", "p.city", "IF(p.hotel_id='',0, p.hotel_id) hotel_id",
			"IF(DATE_FORMAT( FROM_UNIXTIME( p.create_at ), '%Y-%m-%d' ) <= '2021-07-23',1,0) active_status_date",
			"lo.return_status", "IF(lo.status = 3,1,0) active_status")
	db.Joins("left join logistics lo on lo.place_id =s.place_id")
	db.Joins("LEFT JOIN ( SELECT SUM( settlement_money ) settlementMoney, sum( IF ( state = 5, 1, 0 ) ) completeCount,  sum( IF ( state >0, 1, 0 ) ) AS orderCount,place_id, DATE_FORMAT( FROM_UNIXTIME(  end_at ), '%Y-%m' ) as  date,DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m' ) as firs_date FROM orders   " + isDrawAndIsTianHai + "   GROUP BY place_id,date  ORDER BY firs_date asc ) AS o ON o.place_id = s.place_id and  o.date = DATE_FORMAT(s.income_day,'%Y-%m')")
	db.Joins("LEFT JOIN places p ON p.id = s.place_id")
	db.Joins("LEFT JOIN ( SELECT sum(money) incomeTotal,place_id,user_id,DATE_FORMAT( FROM_UNIXTIME(  create_at ), '%Y-%m' ) date FROM dividends_log GROUP BY date, place_id,user_id ) AS dl ON dl.place_id = s.place_id and dl.user_id = p.user_id and dl.date = DATE_FORMAT(s.income_day,'%Y-%m')")
	db.Joins("LEFT JOIN ( select count(1) as activeDevCount,place_id,date  from (SELECT device_sn as total,place_id,DATE_FORMAT( FROM_UNIXTIME(  create_at ), '%Y-%m' ) date FROM orders   " + isDrawAndIsTianHai + "  group by device_sn,place_id,date) orders GROUP BY place_id,date) AS od ON od.place_id = s.place_id and od.date = DATE_FORMAT(s.income_day,'%Y-%m')")

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]
		//月统计
		db.Where("DATE_FORMAT(s.income_day,'%Y-%m') >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m') AND "+
			"DATE_FORMAT(s.income_day,'%Y-%m') <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", startTime, endTime)
	}

	if placeName != "" {
		db.Where("p.place_name = ?", placeName)
	}

	if isAdmin != helper.TypeNumIsAdminOperator {
		db.Where("p.id in(?)", placeIdArr)
	} else {
		isDrawAndIsTianHai = ""
	}
	db.Group("DATE_FORMAT(s.income_day,'%Y-%m'),s.place_id")
	db.Order("s.income_day desc")
	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, list, count)
}
func (d *StatisticalDao) PlaceStatisticsExportAllTotalListDao(userId int, isAdmin, isDraw uint8, placeName string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	var (
		count  int64
		list   []*placeincome.PlaceIncomeExportModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)
	//isDrawSql := ``
	//if isDraw != helper.TypeNumIsDrawOpen {
	//	isDrawSql = ` AND o.is_draw<>` + strconv.Itoa(helper.TypeNumIsDrawOpen) + ` and o.is_tianhai=0`
	//
	//} else {
	//	isDrawSql = ` AND (is_draw<>` + strconv.Itoa(helper.TypeNumIsDrawOpen) + ` or (is_draw=` + strconv.Itoa(helper.TypeNumIsDrawOpen) + ` and agent_user_id>2)) and o.is_tianhai=0`
	//	//db.Where("(is_draw<>? or (is_draw=? and agent_user_id>2)) and o.is_tianhai=0", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen)
	//}

	fields := `p.id place_id,p.create_at place_create_at,p.create_at place_create_at,p.province,p.city,p.place_name,p.hotel_id,l.receive_time,l.return_time,
	firs_date as first_order_date,l.logistics_order_no,IF(FROM_UNIXTIME( p.create_at )<='2021-07-23',1,0) active_status_date,
	l.return_status,IF(l.status = 3,1,0) active_status`
	db := global.Orm.Debug().Table("places p").Select(fields)
	db.Joins("LEFT JOIN (SELECT * FROM logistics GROUP BY place_id) l ON p.id = l.place_id")
	db.Joins("left join (SELECT DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) as firs_date,place_id FROM (SELECT create_at,place_id FROM orders GROUP BY create_at  ORDER BY create_at ASC) orders1  GROUP BY place_id ORDER BY firs_date asc) o on o.place_id =p.id")
	//db.Joins("LEFT JOIN  orders o on p.id = o.place_id  ")
	//db.Joins("LEFT JOIN  (SELECT * FROM orders o Where 1 = 1 " + isDrawSql + " ) o on p.id = o.place_id  ")

	//db.Where("o.is_tianhai=0 AND o.is_draw<>1")
	var placeIdArr []int
	if isAdmin != helper.TypeNumIsAdminOperator {
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placeIdArr = NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

		if len(placeIdArr) == 0 {
			return dingo.ErrorIf(db.Error, list, count)
		}
		count = int64(len(placeIdArr))
		db.Where("p.id in(?)", placeIdArr)

		//if isDraw != helper.TypeNumIsDrawOpen {
		//	db.Where("o.is_draw<>? and o.is_tianhai=0", helper.TypeNumIsDrawOpen)
		//} else {
		//	db.Where("(is_draw<>? or (is_draw=? and agent_user_id>2)) and o.is_tianhai=0", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen)
		//}
	} else {
		if placeName == `` {
			global.Orm.Raw(" select count(1)  FROM places ").Find(&count)
		}
	}

	if placeName != `` {
		db.Where("p.place_name=?", placeName)
		global.Orm.Raw(" select count(1)  FROM places where place_name=?", placeName).Find(&count)
	}

	db.Group("p.id").Order("p.id DESC").Limit(limit).Offset(offset).Find(&list)

	if len(list) == 0 || db.Error != nil {
		return dingo.ErrorIf(db.Error, list, count)
	}

	// 激活设备量/有产设备量/收益/scan_code_user 分批查询
	type countList struct {
		Total   int
		PlaceId int `gorm:"column:place_id"`
	}
	var targetPleceIds []int
	var deviceCountList []countList
	var activeDeviceCountList []countList
	var incomeList []countList
	var scanCodeUserList []countList

	for _, item := range list {
		targetPleceIds = append(targetPleceIds, item.PlaceId)
	}

	deviceCountSql := `SELECT COUNT(1) total, place_id FROM devices WHERE place_id IN (?) GROUP BY place_id`
	activeDeviceCounCountSql := `SELECT COUNT(1) total, place_id FROM (SELECT device_sn, place_id FROM 
	orders WHERE place_id IN (?) GROUP BY place_id,device_sn)o GROUP BY place_id`
	incomeCountSql := `SELECT SUM(dl.money) total,p.id place_id FROM places p LEFT JOIN dividends_log dl ON 
	p.id=dl.place_id AND p.user_id=dl.user_id WHERE p.id IN (?) AND dl.money > 0 GROUP BY p.id,p.user_id`
	scanCodeUserSql := `SELECT COUNT(1) total, place_id FROM (SELECT place_id FROM orders WHERE place_id in (?) 
	GROUP BY place_id,openid) o GROUP BY o.place_id`
	global.Orm.Debug().Raw(deviceCountSql, targetPleceIds).Find(&deviceCountList)
	global.Orm.Debug().Raw(activeDeviceCounCountSql, targetPleceIds).Find(&activeDeviceCountList)
	global.Orm.Debug().Raw(incomeCountSql, targetPleceIds).Find(&incomeList)
	global.Orm.Debug().Raw(scanCodeUserSql, targetPleceIds).Find(&scanCodeUserList)

	for _, item := range list {
		for _, dev := range deviceCountList {
			if dev.PlaceId == item.PlaceId {
				item.DeviceCount = int64(dev.Total)
				item.DeviceTotal = int64(dev.Total)
			}
		}
		for _, adev := range activeDeviceCountList {
			if adev.PlaceId == item.PlaceId {
				item.ActiveDevCount = int64(adev.Total)
			}
		}
		for _, income := range incomeList {
			if income.PlaceId == item.PlaceId {
				item.Income = int64(income.Total)
			}
		}
		for _, codeUser := range scanCodeUserList {
			if codeUser.PlaceId == item.PlaceId {
				item.ScanCodeUser = int64(codeUser.Total)
			}
		}
	}

	ordersMap := map[string]placeincome.StatisticsPlaceOrders{}
	var ordersModel []placeincome.StatisticsPlaceOrders
	//查询网点统计的订单
	ordersSql := "SELECT sum( IF ( state = 5, settlement_money, 0 )  ) AS settlement_money ,sum( IF ( state >0, 1, 0 ) ) AS order_count, SUM( IF ( state = 5, 1, 0 ) ) complete_count, SUM( IF ( state = 3, 1, 0 ) ) cancel_count,place_id,shared_mode FROM orders Where 1= 1 AND is_tianhai=0 AND is_draw<>1  GROUP BY place_id"
	global.Orm.Debug().Raw(ordersSql).Find(&ordersModel)
	for _, v := range ordersModel {
		ordersMap[strconv.Itoa(v.PlaceId)] = v
	}

	//赋值
	for _, lst := range list {
		//订单
		if v, ok := ordersMap[strconv.Itoa(lst.PlaceId)]; ok {
			lst.ScanCount = v.OrderCount
			lst.CompleteCount = v.CompleteCount
			lst.CompleteCount = v.CompleteCount
			lst.SettlementMoney = v.SettlementMoney
		} else {
			lst.ScanCount = 0
			lst.CompleteCount = 0
			lst.CompleteCount = 0
			lst.SettlementMoney = 0
		}

	}

	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) PlaceRealTimeDayStatisticsList(userId int, isAdmin uint8, placeName string, selectTime string, monthType int, sharedMode string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	var (
		count  int64
		list   []*placeincome.PlaceIncomeModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	//Select("s.place_id", "s.settlement_money",
	//	"s.device_total", "s.income_day",
	//	"s.place_name", "lo.receive_time",
	//	"s.income", "s.order_count", "s.complete_count",
	//	"firs_date as first_order_date", "s.scan_code_user",
	//	"p.create_at as place_create_at", "lo.logistics_order_no",
	//	"p.province", "p.city", "IF(p.hotel_id='',0, p.hotel_id) hotel_id",
	//	"lo.return_status", "IF(lo.status = 3,1,0) active_status").
	//	Joins("left join places p on p.id = s.place_id").

	db := global.Orm.Debug().
		Table("place_income s").
		Select("s.id", "s.place_id",
			"s.income_day", "s.device_total",
			"s.agent_user_id", "s.place_name",
			"p.create_at as place_create_at",
			"p.province", "p.city", "IF(p.hotel_id='',0, p.hotel_id) hotel_id").
		Joins("left join places p on p.id = s.place_id")

	if placeName != "" {
		db.Where("p.place_name =? ", placeName)
	}

	selectTimeSql := ""
	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]
		//日统计
		if monthType == 1 {
			selectTimeSql = " AND income_day >= DATE_FORMAT(FROM_UNIXTIME(" + startTime + "),'%Y-%m-%d') And income_day <= DATE_FORMAT(FROM_UNIXTIME(" + endTime + "),'%Y-%m-%d')"

			db.Where("income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", startTime)
			db.Where("income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime)
		} else {
			selectTimeSql = " AND income_day >= DATE_FORMAT(FROM_UNIXTIME(" + startTime + "),'%Y-%m') And income_day <= DATE_FORMAT(FROM_UNIXTIME(" + endTime + "),'%Y-%m')"
			db.Where("income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", startTime)
			db.Where("income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", endTime)
		}

	}
	sharedSql := ""
	if sharedMode != "" {
		sharedSql = " shared_mode = " + sharedMode
		db.Where("s.shared_mode =? ", sharedMode)
	}

	// 如果是运营商或代理商登录，只展示旗下所有商户
	if isAdmin > helper.TypeNumIsAdminStaff {

		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		//分公司
		if isAdmin == helper.TypeNumIsAdminBranch {
			placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)
			placeIdArr = append(placesBranchIds, placesBranchIds...)
			//去重网点
			placeIdArr = utils.RemoveRepByMap(placesBranchIds)
		}
		db.Where("p.id in (?)", placeIdArr)
		//db.Where("u.parent_id = ? ", loginUserId)
	}
	db.Order("income_day desc")
	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)

	var placeIds []int
	for _, model := range list {
		placeIds = append(placeIds, model.PlaceId)
	}
	//去重网点
	placeIds = utils.RemoveRepByMap(placeIds)
	//查询分红
	incomeMap := map[string]int64{}
	var incomeModel []*placeincome.PlaceIncomeModel
	incomeSql := "SELECT SUM(money) as income,DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) as income_day ,user_id as agent_user_id ,place_id FROM dividends_log Where 1= 1 AND place_id in (?) " + selectTimeSql + "  GROUP BY income_day,agent_user_id,place_id"
	global.Orm.Debug().Raw(incomeSql, placeIds).Find(&incomeModel)
	for _, v := range incomeModel {
		incomeMap[strconv.Itoa(v.PlaceId+v.AgentUserId)+v.IncomeDay] = v.Income
	}

	ordersMap := map[string]placeincome.StatisticsPlaceOrders{}
	var ordersModel []placeincome.StatisticsPlaceOrders
	//查询网点统计的订单
	ordersSql := "SELECT sum( settlement_money ) AS settlement_money ,sum( IF ( state >0, 1, 0 ) ) AS order_count, SUM( IF ( state = 5, 1, 0 ) ) complete_count, SUM( IF ( state = 3, 1, 0 ) ) cancel_count,DATE_FORMAT( FROM_UNIXTIME( end_at ), '%Y-%m-%d' ) income_day,place_id,shared_mode FROM orders Where 1= 1 AND place_id in (?) AND is_tianhai=0 AND is_draw<>1 " + sharedSql + selectTimeSql + "  GROUP BY income_day,place_id"
	global.Orm.Debug().Raw(ordersSql, placeIds).Find(&ordersModel)
	for _, v := range ordersModel {
		ordersMap[strconv.Itoa(v.PlaceId)+v.IncomeDay] = v
	}

	//deviceMap := map[int]int64{}
	////查询设备总数
	//var deviceModel []*placeincome.PlaceIncomeModel
	//deviceSql := "SELECT count(1) as device_total,place_id FROM devices GROUP BY place_id"
	//global.Orm.Debug().Raw(deviceSql).Find(&deviceModel)
	//for _, v := range deviceModel {
	//	deviceMap[v.PlaceId] = v.DeviceTotal
	//}

	activeDeviceMap := map[string]int64{}
	//查询激活设备量
	var activeDeviceModel []*placeincome.PlaceIncomeAllModel
	activeDevCountSql := "select count(1) as active_dev_count,place_id,date as income_day  from (SELECT device_sn as total,place_id,DATE_FORMAT( FROM_UNIXTIME(  create_at ), '%Y-%m-%d' ) date FROM orders Where 1=1 AND place_id in (?)   group by device_sn,place_id,date) orders GROUP BY place_id,income_day"
	global.Orm.Debug().Raw(activeDevCountSql, placeIds).Find(&activeDeviceModel)
	for _, v := range activeDeviceModel {
		activeDeviceMap[strconv.Itoa(v.PlaceId)+v.IncomeDay] = v.ActiveDevCount
	}
	//赋值
	for _, lst := range list {
		lst.DeviceCount = lst.DeviceTotal
		//分红收益
		if v, ok := incomeMap[strconv.Itoa(lst.PlaceId+lst.AgentUserId)+lst.IncomeDay]; ok {
			lst.Income = v
		} else {
			lst.ActiveDevCount = 0
		}

		//订单
		if v, ok := ordersMap[strconv.Itoa(lst.PlaceId)+lst.IncomeDay]; ok {
			lst.ScanCount = v.OrderCount
			lst.CompleteCount = v.CompleteCount
			lst.CompleteCount = v.CompleteCount
			lst.SettlementMoney = v.SettlementMoney
		} else {
			lst.ScanCount = 0
			lst.CompleteCount = 0
			lst.CompleteCount = 0
			lst.SettlementMoney = 0
		}

		//扫码量
		if v, ok := activeDeviceMap[strconv.Itoa(lst.PlaceId)+lst.IncomeDay]; ok {
			lst.ActiveDevCount = v
		} else {
			lst.ActiveDevCount = 0
		}
	}
	return dingo.ErrorIf(db.Error, list, count)
}

func (d *StatisticalDao) PlaceRealTimeMonthStatisticsList(userId int, isAdmin uint8, placeName string, selectTime string, monthType int, sharedMode string, baseListReq *request.BaseListReq) *dingo.ErrorWrap {
	var (
		count  int64
		list   []*placeincome.PlaceIncomeModel
		limit  = baseListReq.PageSize
		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
	)

	db := global.Orm.Debug().
		Table("place_income s").
		Select("s.id", "s.place_id",
			"s.income_day", "s.device_total", "s.agent_user_id",
			"DATE_FORMAT(s.income_day,'%Y-%m') as income_day", "s.place_name",
			"p.create_at as place_create_at",
			"p.province", "p.city", "IF(p.hotel_id='',0, p.hotel_id) hotel_id").
		Joins("left join places p on p.id = s.place_id")

	if placeName != "" {
		db.Where("p.place_name =? ", placeName)
	}

	if selectTime != "" {
		selectTimeArr := strings.Split(selectTime, ",")
		startTime := selectTimeArr[0]
		endTime := selectTimeArr[1]
		//日统计
		if monthType == 1 {
			db.Where("income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", startTime)
			db.Where("income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime)
		} else {
			db.Where("income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", startTime)
			db.Where("income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", endTime)
		}

	}

	if sharedMode != "" {
		db.Where("s.shared_mode =? ", sharedMode)
	}

	// 如果是运营商或代理商登录，只展示旗下所有商户
	if isAdmin > helper.TypeNumIsAdminStaff {

		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		//分公司
		if isAdmin == helper.TypeNumIsAdminBranch {
			placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)
			placeIdArr = append(placesBranchIds, placesBranchIds...)
			//去重网点
			placeIdArr = utils.RemoveRepByMap(placesBranchIds)
		}
		db.Where("p.id in (?)", placeIdArr)
		//db.Where("u.parent_id = ? ", loginUserId)
	}
	db.Order("income_day desc")

	db.Group("DATE_FORMAT(s.income_day,'%Y-%m'),s.place_id")
	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)

	var placeIds []int
	for _, model := range list {
		placeIds = append(placeIds, model.PlaceId)
	}
	//去重网点
	placeIds = utils.RemoveRepByMap(placeIds)
	//查询分红
	incomeMap := map[string]int64{}
	var incomeModel []*placeincome.PlaceIncomeModel
	incomeSql := "SELECT SUM(money) as income,DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m' ) as income_day ,user_id as agent_user_id ,place_id FROM dividends_log Where 1= 1  AND place_id in (?)  GROUP BY income_day,agent_user_id,place_id"
	global.Orm.Debug().Raw(incomeSql, placeIds).Find(&incomeModel)
	for _, v := range incomeModel {
		incomeMap[strconv.Itoa(v.PlaceId+v.AgentUserId)+v.IncomeDay] = v.Income
	}

	ordersMap := map[string]placeincome.StatisticsPlaceOrders{}
	var ordersModel []placeincome.StatisticsPlaceOrders
	//查询网点统计的订单
	ordersSql := "SELECT sum( IF ( state = 5, settlement_money, 0 )  ) AS settlement_money ,sum( IF ( state >0, 1, 0 ) ) AS order_count, SUM( IF ( state = 5, 1, 0 ) ) complete_count, SUM( IF ( state = 3, 1, 0 ) ) cancel_count,DATE_FORMAT( FROM_UNIXTIME( end_at ), '%Y-%m' ) income_day,place_id,shared_mode FROM orders Where 1= 1 AND place_id in (?)  AND is_tianhai=0 AND is_draw<>1  GROUP BY income_day,place_id"
	global.Orm.Debug().Raw(ordersSql, placeIds).Find(&ordersModel)
	for _, v := range ordersModel {
		ordersMap[strconv.Itoa(v.PlaceId)+v.IncomeDay] = v
	}

	//deviceMap := map[int]int64{}
	////查询设备总数
	//var deviceModel []*placeincome.PlaceIncomeModel
	//deviceSql := "SELECT count(1) as device_total,place_id FROM devices GROUP BY place_id"
	//global.Orm.Debug().Raw(deviceSql).Find(&deviceModel)
	//for _, v := range deviceModel {
	//	deviceMap[v.PlaceId] = v.DeviceTotal
	//}

	activeDeviceMap := map[string]int64{}
	//查询激活设备量
	var activeDeviceModel []*placeincome.PlaceIncomeAllModel
	activeDevCountSql := "select count(1) as active_dev_count,place_id,date as income_day  from (SELECT device_sn as total,place_id,DATE_FORMAT( FROM_UNIXTIME(  create_at ), '%Y-%m' ) date FROM orders Where 1=1 AND place_id in (?)   group by device_sn,place_id,date) orders GROUP BY place_id,income_day"
	global.Orm.Debug().Raw(activeDevCountSql, placeIds).Find(&activeDeviceModel)
	for _, v := range activeDeviceModel {
		activeDeviceMap[strconv.Itoa(v.PlaceId)+v.IncomeDay] = v.ActiveDevCount
	}
	//赋值
	for _, lst := range list {

		lst.DeviceCount = lst.DeviceTotal
		//分红收益
		if v, ok := incomeMap[strconv.Itoa(lst.PlaceId+lst.AgentUserId)+lst.IncomeDay]; ok {
			lst.Income = v
		} else {
			lst.ActiveDevCount = 0
		}

		//订单
		if v, ok := ordersMap[strconv.Itoa(lst.PlaceId)+lst.IncomeDay]; ok {
			lst.ScanCount = v.OrderCount
			lst.CompleteCount = v.CompleteCount
			lst.CompleteCount = v.CompleteCount
			lst.SettlementMoney = v.SettlementMoney
		} else {
			lst.ScanCount = 0
			lst.CompleteCount = 0
			lst.CompleteCount = 0
			lst.SettlementMoney = 0
		}

		////设备
		//if v, ok := deviceMap[lst.PlaceId]; ok {
		//	lst.DeviceTotal = v
		//} else {
		//	lst.DeviceTotal = 0
		//}

		//扫码量
		if v, ok := activeDeviceMap[strconv.Itoa(lst.PlaceId)+lst.IncomeDay]; ok {
			lst.ActiveDevCount = v
		}
	}
	return dingo.ErrorIf(db.Error, list, count)
}

//func (d *StatisticalDao) BranchRealTimeDayStatisticsList(userName string, selectTime string, monthType int, sharedMode string, baseListReq *request.BaseListReq, loginUserId int, isAdmin uint8, isPlace uint8) *dingo.ErrorWrap {
//	var (
//		count  int64
//		list   []agentincome.BranchIncomeModel
//		limit  = baseListReq.PageSize
//		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
//	)
//	db := global.Orm.Debug().Table("branch_income b").
//		Select("b.*,u.name as name,u.user_name as agent_user_name,u.phone as phone").
//		Joins("LEFT JOIN ( SELECT u.id, u.name,u.user_name,u.phone FROM users u) AS u ON  u.id = b.agent_user_id")
//
//	if userName != "" {
//		db.Where("agent_user_name = ? ", userName)
//	}
//	if sharedMode != "" {
//		db.Where("shared_mode = ? ", userName)
//	}
//
//	if selectTime != "" {
//		selectTimeArr := strings.Split(selectTime, ",")
//		startTime := selectTimeArr[0]
//		endTime := selectTimeArr[1]
//		//日统计
//		if monthType == 1 {
//			db.Where("income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", startTime)
//			db.Where("income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", endTime)
//		} else {
//			db.Where("income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", startTime)
//			db.Where("income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')", endTime)
//		}
//	}
//
//	// 如果是运营商或代理商登录，只展示旗下所有商户
//	if isPlace == 3 {
//
//		// 获取该用户下的所有代理商的用户ID
//		pidArr := []int{loginUserId}
//		userIdArr := make([]int, 0)
//		userIdArr = append(userIdArr, loginUserId)
//		isRecursive := true
//		// 递归 无限查询下级
//		for isRecursive {
//			tempUserIdArr := NewUserDao().GetUserIdByPid(pidArr).Unwrap().([]int)
//
//			if len(tempUserIdArr) == 0 {
//				isRecursive = false
//			} else {
//				userIdArr = append(userIdArr, tempUserIdArr...)
//				pidArr = tempUserIdArr
//				//log.Println("当前pid数组：",pidArr)
//				//log.Println("当前userIdArr数组：",userIdArr)
//			}
//		}
//		db.Where("agent_user_id in (?)", userIdArr)
//		//db.Where("u.parent_id = ? ", loginUserId)
//	}
//
//	if monthType == 2 {
//		db.Group("date_format( income_day, '%Y-%m' ),agent_user_id")
//	}
//	db.Order("income_day desc")
//	db.Limit(limit).Offset(offset).Find(&list).Limit(-1).Offset(-1).Count(&count)
//	var userIds []int
//	for _, model := range list {
//		userIds = append(userIds, model.BranchUserId)
//	}
//	//查询分红
//	incomeMap := map[string]int64{}
//	var incomeModel []*agentincome.BranchIncomeModel
//	incomeSql := "SELECT SUM(money) as total_money,DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) as income_day ,user_id as agent_user_id  FROM dividends_log Where 1= 1  AND user_id in (?)  GROUP BY income_day,agent_user_id"
//	global.Orm.Debug().Raw(incomeSql, userIds).Find(&incomeModel)
//	for _, v := range incomeModel {
//		incomeMap[strconv.Itoa(v.BranchUserId)+v.IncomeDay] = v.TotalMoney
//	}
//
//	ordersMap := map[string]agentincome.BranchIncomeOrders{}
//	var ordersModel []agentincome.BranchIncomeOrders
//
//	//查询网点统计的订单
//	ordersSql := `SELECT
//	o.trade_no,
//	sum( o.settlement_money ) AS trade_total,
//	sum( IF ( o.state > 0, 1, 0 ) ) AS order_count,
//	SUM( IF ( o.state = 5, 1, 0 ) ) complete_count,
//	SUM( IF ( o.state = 3, 1, 0 ) ) cancel_count,
//	DATE_FORMAT( FROM_UNIXTIME( o.end_at ), '%Y-%m-%d' ) as income_day,
//	dl.user_id,
//	shared_mode
//	FROM
//		orders o
//		LEFT JOIN (  SELECT trade_no,user_id, DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) as date FROM dividends_log WHERE 1=1 and user_id in(?) GROUP BY date,trade_no ) dl on dl.trade_no = o.trade_no and dl.date  =  DATE_FORMAT( FROM_UNIXTIME( o.end_at ), '%Y-%m-%d' )
//		WHERE 1=1
//		and dl.user_id  IS NOT NULL
//		GROUP BY
//		dl.user_id,
//		income_day `
//	global.Orm.Debug().Raw(ordersSql, userIds).Find(&ordersModel)
//	for _, v := range ordersModel {
//		ordersMap[strconv.Itoa(v.UserId)+v.IncomeDay] = v
//	}
//
//	for _, lst := range list {
//		//分红收益
//		if v, ok := incomeMap[strconv.Itoa(lst.BranchUserId)+lst.IncomeDay]; ok {
//			lst.TotalMoney = v
//		} else {
//			lst.TotalMoney = 0
//		}
//
//		//订单
//		if v, ok := ordersMap[strconv.Itoa(lst.BranchUserId)+lst.IncomeDay]; ok {
//			lst.OrderCount = v.OrderCount
//			lst.CompleteCount = v.CompleteCount
//			lst.CompleteCount = v.CompleteCount
//			lst.TradeTotal = v.TradeTotal
//		} else {
//			lst.OrderCount = 0
//			lst.CompleteCount = 0
//			lst.CompleteCount = 0
//			lst.TradeTotal = 0
//		}
//
//		////扫码量
//		//if v, ok := activeDeviceMap[strconv.Itoa(lst.PlaceId)+lst.IncomeDay]; ok {
//		//	lst.ActiveDevCount = v
//		//} else {
//		//	lst.ActiveDevCount = 0
//		//}
//	}
//	return dingo.ErrorIf(db.Error, list, count)
//}

//func (d *StatisticalDao) OperatingInternalList(userId int, isAdmin uint8, selectTime string, sharedMode string, baseListReq *request.BaseListReq) *request.BaseListReq {
//	var (
//		count  int64
//		lst    []*users.OperatingInternal
//		limit  = baseListReq.PageSize
//		offset = baseListReq.PageSize * (baseListReq.PageNo - 1)
//	)
//	db := global.Orm.Table("dividends_log")
//	if userId > 0 {
//		db.Where("user_id = ? ", userId)
//	}
//
//	if sharedMode != "" {
//		db.Where("shared_mode =? ", sharedMode)
//	}
//
//	if selectTime != "" {
//		selectTimeArr := strings.Split(selectTime, ",")
//		startTime := selectTimeArr[0]
//		endTime := selectTimeArr[1]
//		db.Where("date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') ", startTime)
//		db.Where("date_format(FROM_UNIXTIME(create_at), '%Y-%m-%d ') <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') ", endTime)
//	}
//}
